from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from database.database import get_db
from core.base.api_mode import ApiResponse, api_success
from modules.system.schemas.data_permission_schemas import (
    DataPermissionRuleCreate, DataPermissionRuleUpdate,
    RoleDataPermissionCreate, RoleDataPermissionBatchCreate
)
from modules.system.params.data_permission_params import DataPermissionRuleQuery, RoleDataPermissionQuery
from modules.system.services.data_permission_service import DataPermissionRuleService, RoleDataPermissionService
from modules.system.vos.data_permission_vo import (
    DataPermissionRuleResponse, DataPermissionRuleListResponse,
    RoleDataPermissionResponse, RoleDataPermissionRulesResponse
)
from typing import List
from core.pagination import DependsPagination, PageData

router = APIRouter()


# 数据权限规则相关接口
@router.post("/rules/create", response_model=ApiResponse[DataPermissionRuleResponse], summary="创建数据权限规则")
async def create_rule(payload: DataPermissionRuleCreate, db: AsyncSession = Depends(get_db)):
    """创建数据权限规则"""
    rule = await DataPermissionRuleService.create_rule(db, payload)
    return api_success(data=rule, msg="创建成功")


@router.post(
    "/rules/list", 
    response_model=ApiResponse[PageData[DataPermissionRuleResponse]],
    summary="获取数据权限规则列表",
    dependencies=[DependsPagination],
)
async def list_rules(query_params: DataPermissionRuleQuery, db: AsyncSession = Depends(get_db)):
    """获取数据权限规则列表"""
    result = await DataPermissionRuleService.get_rules_with_pagination(db, query_params)
    return api_success(
        data=result,
        msg="获取成功",
    )


@router.get("/rules/{rule_id}", response_model=ApiResponse[DataPermissionRuleResponse], summary="获取数据权限规则详情")
async def get_rule(rule_id: int, db: AsyncSession = Depends(get_db)):
    """获取数据权限规则详情"""
    rule = await DataPermissionRuleService.get_rule_by_id(db, rule_id)
    if not rule:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="数据权限规则不存在")
    return api_success(data=rule, msg="获取成功")


@router.put("/rules/{rule_id}", response_model=ApiResponse[DataPermissionRuleResponse], summary="更新数据权限规则")
async def update_rule(rule_id: int, payload: DataPermissionRuleUpdate, db: AsyncSession = Depends(get_db)):
    """更新数据权限规则"""
    rule = await DataPermissionRuleService.update_rule(db, rule_id, payload)
    return api_success(data=rule, msg="更新成功")


@router.delete("/rules/{rule_id}", response_model=ApiResponse[dict], summary="删除数据权限规则")
async def delete_rule(rule_id: int, db: AsyncSession = Depends(get_db)):
    """删除数据权限规则"""
    await DataPermissionRuleService.delete_rule(db, rule_id)
    return api_success({"message": f"数据权限规则ID {rule_id} 删除成功"}, msg="删除成功")


@router.get("/rules/table/{table_name}", response_model=ApiResponse[List[DataPermissionRuleResponse]], summary="根据表名获取数据权限规则")
async def get_rules_by_table(table_name: str, db: AsyncSession = Depends(get_db)):
    """根据表名获取数据权限规则"""
    rules = await DataPermissionRuleService.get_by_table_name(db, table_name)
    return api_success(data=rules, msg="获取成功")


# 角色数据权限关联相关接口
@router.post("/role-permissions/create", response_model=ApiResponse[RoleDataPermissionResponse], summary="创建角色数据权限关联")
async def create_role_permission(payload: RoleDataPermissionCreate, db: AsyncSession = Depends(get_db)):
    """创建角色数据权限关联"""
    permission = await RoleDataPermissionService.create_role_permission(db, payload)
    return api_success(data=permission, msg="创建成功")


@router.post("/role-permissions/batch", response_model=ApiResponse[List[RoleDataPermissionResponse]], summary="批量创建角色数据权限关联")
async def batch_create_role_permissions(payload: RoleDataPermissionBatchCreate, db: AsyncSession = Depends(get_db)):
    """批量创建角色数据权限关联"""
    permissions = await RoleDataPermissionService.batch_create_role_permissions(db, payload)
    return api_success(data=permissions, msg="批量创建成功")


@router.get("/role-permissions/role/{role_id}", response_model=ApiResponse[RoleDataPermissionRulesResponse], summary="获取角色的数据权限规则")
async def get_role_permissions(role_id: int, db: AsyncSession = Depends(get_db)):
    """获取角色的数据权限规则"""
    permissions = await RoleDataPermissionService.get_by_role_id(db, role_id)
    rule_ids = [p.rule_id for p in permissions]
    return api_success(RoleDataPermissionRulesResponse(role_id=role_id, rule_ids=rule_ids), msg="获取成功")


@router.get("/role-permissions/rules/{role_id}", response_model=ApiResponse[List[DataPermissionRuleResponse]], summary="获取角色关联的数据权限规则详情")
async def get_role_rules(role_id: int, db: AsyncSession = Depends(get_db)):
    """获取角色关联的数据权限规则详情"""
    rules = await RoleDataPermissionService.get_role_rules(db, role_id)
    return api_success(data=rules, msg="获取成功")


@router.get("/role-permissions/rule/{rule_id}", response_model=ApiResponse[List[RoleDataPermissionResponse]], summary="获取使用指定规则的角色关联列表")
async def get_rule_role_permissions(rule_id: int, db: AsyncSession = Depends(get_db)):
    """获取使用指定规则的角色关联列表"""
    permissions = await RoleDataPermissionService.get_by_rule_id(db, rule_id)
    return api_success(data=permissions, msg="获取成功")


@router.delete("/role-permissions/role/{role_id}", response_model=ApiResponse[dict], summary="删除角色的所有数据权限关联")
async def delete_role_permissions(role_id: int, db: AsyncSession = Depends(get_db)):
    """删除角色的所有数据权限关联"""
    await RoleDataPermissionService.delete_role_permissions(db, role_id)
    return api_success({"message": f"角色ID {role_id} 的数据权限关联删除成功"}, msg="删除成功")


@router.delete("/role-permissions/{permission_id}", response_model=ApiResponse[dict], summary="删除单个角色数据权限关联")
async def delete_role_permission(permission_id: int, db: AsyncSession = Depends(get_db)):
    """删除单个角色数据权限关联"""
    await RoleDataPermissionService.delete_role_permission(db, permission_id)
    return api_success({"message": f"角色数据权限关联ID {permission_id} 删除成功"}, msg="删除成功")